<template>
  <div>
    测试shallowReactive的值变化：
    {{ state5.c }}
  </div>
</template>

<script setup>
  import { reactive, toRef, isReactive, toRefs, unref, readonly, ref, shallowRef, shallowReactive, isRef, isProxy, toValue } from "vue";
  //ref相关

  /* toRef：基于响应式对象的某一个属性，将其转换为 ref 值 */
  const state = reactive({
    count: 0,
    name: {
      firstName: 'zeng'
    }
  })

  const countRef = toRef(state, 'count')
  // 这里其实就等价于 ref(state.count)
  console.log(countRef);
  console.log(countRef.value);

  console.log(isReactive(state));
  console.log(isReactive(state.name));
  const nameRef = toRef(state.name)
  // 这里其实就等价于 ref(state.name)
  console.log(nameRef);
  console.log(nameRef.value.firstName);


  /*  toRefs:将一个响应式对象转成普通对象，普通对象的每个属性对应的是ref的值*/
  const state1 = reactive({
    count: 0,
    message: 'hello'
  })

  const state1Ref = toRefs(state1)
  console.log('toRefs转换的reactive对象', state1Ref);
  console.log(state1Ref.count.value);
  console.log(state1Ref.message.value);

  /* unRef: 如果参数给的是一个 ref 值，那么就返回内部的值，如果不是 ref，那么就返回参数本身 */
  const normalValue = 20
  console.log(unref(state1Ref.count));
  console.log(unref(normalValue));

  /* 只读代理 */
  const lastsName = ref(123)
  const readOnlyName = readonly(lastsName)
  // console.log('只读属性', readOnlyName++);


  //判断相关
  const obj = {
    a: 1,
    b: 2,
    c: {
      d: 3,
      e: 4
    }
  }
  const state2 = ref(obj)
  const state3 = shallowRef(obj)
  const state4 = reactive(obj)
  const state5 = shallowReactive(obj)
  console.log(isRef(state2))   //true
  console.log(isRef(state3))   //true
  console.log(isRef(state2.value.c)) //false
  console.log(isRef(state3.value.c)) //false
  console.log(isReactive(state2.value.c))  //true
  console.log(isReactive(state3.value.c))//false
  console.log(isReactive(state4))//true
  console.log(isReactive(state5))//true
  console.log(isReactive(state4.c))//true
  console.log(state5);
  console.log(state5.c);
  console.log(isReactive(state5.c))//false,c目前只是一个普通的对象

  setTimeout(() => {
    // state5.c.d++
    state5.c = {
      d: 6,
      e: 7
    }
  }, 1000);


  /* isProxy: 检查一个对象是否由 reactive、readonly、shallowReactive、shallowReadonly 创建的代理 */
  // 创建 reactive 代理对象
  const reactiveObject = reactive({ message: 'Hello' })
  // 创建 readonly 代理对象
  const readonlyObject = readonly({ message: 'Hello' })
  console.log(isProxy(reactiveObject)) // true
  console.log(isProxy(readonlyObject)) // true

  /* toValue */
  const ageRef = ref(20)
  const personRef = ref({
    name: 'zqs',
    age: 18
  })
  console.log(toValue(ageRef));
  console.log(toValue(personRef));

  /* toValue 相比 unref 更加灵活一些，它支持传入 getter 函数，并且返回函数的执行结果 */
  const getter = () => 30
  console.log('得到getter函数的返回值', toValue(getter));
</script>

<style lang="scss" scoped></style>
